//
//  XBRequest.m
//  BaiDang
//
//  Created by 硕影 on 2017/7/18.
//  Copyright © 2017年 NetTest. All rights reserved.
//

#import "XBRequest.h"
#import <CommonCrypto/CommonDigest.h>
static XBRequest *_sharedInstance = nil;

@interface XBRequest()

@end

@implementation XBRequest

+ (instancetype)sharedInstance{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[self alloc] init];
    });
    return _sharedInstance;
}

#pragma mark - POST
- (void)postDataWithUrl:(NSString *)url Parameter:(NSDictionary *)param ResponseObject:(void(^)(NSDictionary *responseResult))responseObjects{
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    // 2.设置非校验证书模式
    sessionManager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    sessionManager.securityPolicy.allowInvalidCertificates = YES;
    [sessionManager.securityPolicy setValidatesDomainName:NO];
    
    [sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    sessionManager.requestSerializer.timeoutInterval = 10.f;
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript", nil];
    
    if ([YLUserInfo isLogIn]) {
        [sessionManager.requestSerializer setValue:[YLUserInfo shareUserInfo].token forHTTPHeaderField:@"usertoken"];
    }
    NSString *str = @"";
    if (NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_9_0) {
        str = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }else{
        str = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }

    [sessionManager POST:str parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultDic = (NSDictionary *)result;
            if ([resultDic[@"returnCode"] integerValue] == 4000) {
                [self VerificationLoginStateWithResuleDic:resultDic];
                return ;
            }
            responseObjects(resultDic);
            
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSDictionary *temDic = @{@"resError":error};
        responseObjects(temDic);
    }];
}

#pragma mark - POST
- (void)postDataWithUrl:(NSString *)url Parameter:(NSDictionary *)param contentType:(NSString *)contentType ResponseObject:(void(^)(NSDictionary *responseResult))responseObjects{
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    // 2.设置非校验证书模式
    sessionManager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    
    sessionManager.securityPolicy.allowInvalidCertificates = YES;
    [sessionManager.securityPolicy setValidatesDomainName:NO];
    [sessionManager.requestSerializer setValue:contentType forHTTPHeaderField:@"Content-Type"];
    
    sessionManager.requestSerializer.timeoutInterval = 10.f;
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript", nil];
    if ([YLUserInfo isLogIn]) {
        [sessionManager.requestSerializer setValue:[YLUserInfo shareUserInfo].token forHTTPHeaderField:@"usertoken"];
    }
    NSString *str = @"";
    if (NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_9_0) {
        str = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }else{
        str = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    
    [sessionManager POST:str parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultDic = (NSDictionary *)result;
            if ([resultDic[@"returnCode"] integerValue] == 4000) {
                //登录超时 重新登录
                [self VerificationLoginStateWithResuleDic:resultDic];

                return ;
            }
            responseObjects(resultDic);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSDictionary *temDic = @{@"resError":error};
        responseObjects(temDic);
    }];
}


#pragma mark - GET
- (void)getDataWithUrl:(NSString *)url Parameter:(NSDictionary *)param ResponseObject:(void(^)(NSDictionary *responseResult))responseObjects{
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    // 注意写法的变化
//    sessionManager.securityPolicy=  [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
//    // 2.设置证书模式
//    NSString * cerPath = [[NSBundle mainBundle] pathForResource:@"m.yunxiangguan.cn" ofType:@"cer"];
//    NSData * cerData = [NSData dataWithContentsOfFile:cerPath];
//    sessionManager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate withPinnedCertificates:[[NSSet alloc] initWithObjects:cerData, nil]];
//    // 客户端是否信任非法证书
//    sessionManager.securityPolicy.allowInvalidCertificates = YES;
//    // 是否在证书域字段中验证域名
//    [sessionManager.securityPolicy setValidatesDomainName:NO];

    // 2.设置非校验证书模式
    sessionManager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    sessionManager.securityPolicy.allowInvalidCertificates = YES;
    [sessionManager.securityPolicy setValidatesDomainName:NO];

    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [sessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

    sessionManager.requestSerializer.timeoutInterval = 10.f;
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript",@"text/plain",@"image/png", nil];
    if ([YLUserInfo isLogIn]) {
        [sessionManager.requestSerializer setValue:[YLUserInfo shareUserInfo].token forHTTPHeaderField:@"usertoken"];
    }
    NSString *str = @"";
    if (NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_9_0) {
        str = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }else{
        str = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    
    [sessionManager GET:str parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultDic = (NSDictionary *)result;
            if ([resultDic[@"returnCode"] integerValue] == 4000) {
                //登录超时 重新登录
                [self VerificationLoginStateWithResuleDic:resultDic];

                return ;
            }
            responseObjects(resultDic);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSDictionary *temDic = @{@"resError":error};
        responseObjects(temDic);
    }];
}

#pragma mark - GET
- (void)getDataWithUrl:(NSString *)url Parameter:(NSDictionary *)param contentType:(NSString *)contentType ResponseObject:(void(^)(NSDictionary *responseResult))responseObjects{
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    
    // 2.设置非校验证书模式
    sessionManager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    sessionManager.securityPolicy.allowInvalidCertificates = YES;
    [sessionManager.securityPolicy setValidatesDomainName:NO];
    
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [sessionManager.requestSerializer setValue:contentType forHTTPHeaderField:@"Content-Type"];
    
    sessionManager.requestSerializer.timeoutInterval = 10.f;
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript",@"text/plain",@"image/png", nil];
    
    if ([YLUserInfo isLogIn]) {
        [sessionManager.requestSerializer setValue:[YLUserInfo shareUserInfo].token forHTTPHeaderField:@"usertoken"];
    }
    
    NSString *str = @"";
    if (NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_9_0) {
        str = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }else{
        str = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    
    [sessionManager GET:str parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultDic = (NSDictionary *)result;
            if ([resultDic[@"returnCode"] integerValue] == 4000) {
                //登录超时 重新登录
                [self VerificationLoginStateWithResuleDic:resultDic];
                return ;
            }
            responseObjects(resultDic);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSDictionary *temDic = @{@"resError":error};
        responseObjects(temDic);
    }];
}

#pragma mark - PUT
- (void)putDataWithUrl:(NSString *)url Parameter:(NSDictionary *)param ResponseObject:(void(^)(NSDictionary *responseResult))responseObjects{
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    sessionManager.requestSerializer.timeoutInterval = 10.f;
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript", nil];
    
    if ([YLUserInfo isLogIn]) {
        [sessionManager.requestSerializer setValue:[YLUserInfo shareUserInfo].token forHTTPHeaderField:@"usertoken"];
    }
    NSString *str = @"";
    if (NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_9_0) {
        str = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }else{
        str = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    [sessionManager PUT:str parameters:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultDic = (NSDictionary *)result;
            responseObjects(resultDic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSDictionary *temDic = @{@"resError":error};
        responseObjects(temDic);
    }];
    
}
#pragma mark - DELETE
- (void)deleteDataWithUrl:(NSString *)url Parameter:(NSDictionary *)param ResponseObject:(void(^)(NSDictionary *responseResult))responseObjects{
    
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    sessionManager.requestSerializer.timeoutInterval = 10.f;
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript", nil];
    
    if ([YLUserInfo isLogIn]) {
        [sessionManager.requestSerializer setValue:[YLUserInfo shareUserInfo].token forHTTPHeaderField:@"usertoken"];

    }
    NSString *str = @"";
    if (NSFoundationVersionNumber < NSFoundationVersionNumber_iOS_9_0) {
        str = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }else{
        str = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }
    [sessionManager DELETE:str parameters:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        if ([result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *resultDic = (NSDictionary *)result;
            responseObjects(resultDic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSDictionary *temDic = @{@"resError":error};
        responseObjects(temDic);
    }];
    
}

- (void)VerificationLoginStateWithResuleDic:(NSDictionary *)dic{
    //登录超时 重新登录
    [EasyShowLodingView hidenLoding];
    if ([[[AppDelegate sharedAppDelegate] topViewController] isKindOfClass:NSClassFromString(@"LoginViewController")]) {
        return;
    }
    [YLUserInfo logout];
    if ([[[AppDelegate sharedAppDelegate] topViewController] isKindOfClass:NSClassFromString(@"ZTQuantitativeTradeViewController")]) {
        ZTTabBarController *tab = (ZTTabBarController *)[AppDelegate sharedAppDelegate].window.rootViewController;
        tab.selectedIndex = 0;
    }
    LoginViewController *login = [[LoginViewController alloc] init];

    ZTNavigationController *nav = (ZTNavigationController *)[[AppDelegate sharedAppDelegate] navigationViewController];
    if (nav.viewControllers.count > 1) {
        [nav popToRootViewControllerAnimated:NO];
    }
    [[AppDelegate sharedAppDelegate] pushViewController:login];

    [[UIApplication sharedApplication].keyWindow makeToast:dic[@"returnMessage"] duration:1.5 position:CSToastPositionCenter];
}

- (void)dealloc{
    NSLog(@"HTTPRequest dealloc");
}

@end
